<script lang="ts" setup>
import {computed, ref, getCurrentInstance, onMounted, watch,h} from "vue";
import {HotTable} from "@handsontable/vue3";
import {registerAllModules} from "handsontable/registry";
//注册自定义验证器
import { registerValidator } from 'handsontable/validators';
import "handsontable/dist/handsontable.full.css";
import {registerLanguageDictionary, zhCN,} from 'handsontable/i18n';
import {alignHeaders, addClassesToRows} from "./hooks-callbacks";

const instance = getCurrentInstance();
// register Handsontable's modules
registerAllModules();
registerLanguageDictionary(zhCN);

const props = defineProps({
  columns: {
    type: Array,
    default: () => [],
  },
  checkboxData:{
    type: Array,
    default: () => [],
  },
  records: {
    type: Array,
    default: () => [],
  }, 
  minSpareRows: {
    type: Number,
    default: 5,
  },
  modelValue: [String, Number, Boolean, Array, Object]
});

const parentVisibleHeight = ref(500)
const hotInstanceRef = ref()

const alignHeadersProp = computed(() => alignHeaders);
const addClassesToRowsProp = computed(() => addClassesToRows);
const hiddenColus=()=>{
  let list=[]
  props.columns.forEach((item, index) => {
    if(props.checkboxData.includes(item.data)){
      list.push(index)
    }
  })
  return list
}
const afterChangeMe =(changes,source)=>{
  if(changes){
    // let isCopt=false
    props.records.forEach((data, index) => {
      if(data.shipment_no==changes[0][3]){
        if(props.modelValue[index].shipment_no==data.shipment_no){
          let item=JSON.parse(JSON.stringify(props.modelValue[index]))
          item.fee_type_desc=''
          item.business_at=''
          item.fee_type_desc=''
          item.currency_desc= ''
          item.unit_desc= ''
          item.unit_amount= '1'
          item.memo=''
          item.remark=''
          item.message=''
          props.modelValue[changes[0][0]]=item
          // isCopt=true
          
        }
      }   
    })

  }
}

const getHeight = computed(() => {
  let value = arguments[0]['modelValue'];
  const lineHeight = 25;
  const height = value.length * lineHeight > parentVisibleHeight.value ? parentVisibleHeight.value : value.length * lineHeight + 55
  return height + 'px'
})
const settings = computed(() => {
  return {
    contextMenu: {
      items: {
        'row_above': {},
        'row_below': {},
        'remove_row': {},
        'undo': {},
        'redo': {},
        'make_read_only': {},
      }
    },
    minSpareRows: props.minSpareRows,
    columns: props.columns.map(i => {
      let column = JSON.parse(JSON.stringify(i))
      column.title = getTitle(column)
      return column
    }),
    data: props.modelValue,
    hiddenColumns: {
      columns: hiddenColus(), // 隐藏索引的列
      indicators: true
    },
    afterSelectionEnd:function (row,col){
      // let hotInstanceMain=hotInstanceRef.value.hotInstance
      // hotInstanceMain.getActiveEditor().beginEditing();
    }
  }
})
//自定义验证器
registerValidator('validate',(value,callback)=>{
  let iscallback=false
  props.records.map(j=>{
    if(j.shipment_no==value){
      iscallback=true
    }
  })
  callback(iscallback)
})
onMounted(() => {
  const parentRect = getElementClientRect(instance?.parent?.proxy);
  parentVisibleHeight.value = Math.max(window.innerHeight - parentRect?.top - 180, 500);
})

const getTitle = (column) => {
  return column.title + (column.required ? "<span class='require'>*</span>" : '');
};

const getElementClientRect = (ele) => {
  if (typeof ele?.$el.getBoundingClientRect === 'function') {
    return ele?.$el?.getBoundingClientRect();
  }
  return {top: 0}
}
watch(() => props.modelValue, (data) => {
  hotInstanceRef.value.hotInstance.updateSettings({
    data: data,
  });
}, {deep: true})
// todo 阻止 TAB 换行
</script>

<template>
  <HotTable
      class="w-full"
      language="zh-CN"
      :rowHeaders="true"
      :height="getHeight"
      width="100%"
      stretchH="all"
      :afterGetColHeader="alignHeadersProp"
      :afterChange ="afterChangeMe"
      :beforeRenderer="addClassesToRowsProp"
      :autoWrapRow="true"
      :autoWrapCol="true"
      :settings="settings"
      ref="hotInstanceRef"
      licenseKey="non-commercial-and-evaluation"
  >
  </HotTable>
</template>

<style>
.colHeader .require {
  color: red;
  font-size: 12px;
  margin-left: 5px;
  position: relative;
  top: -2px;
}
</style>